package cn.kgc.tangcco.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpConfig;
import cn.hutool.extra.ftp.FtpMode;
import cn.hutool.setting.dialect.Props;
import cn.kgc.tangcco.model.ResposeText;
import cn.kgc.tangcco.model.ResultCode;
import cn.kgc.tangcco.utils.aliyun.oss.BaseAliOSSUtil;
import cn.kgc.tangcco.utils.date.BaseDateUtil;
import cn.kgc.tangcco.utils.fdfs.BaseFastDFSUtil;
import cn.kgc.tangcco.utils.ftp.BaseFtpClient;
import cn.kgc.tangcco.utils.localdatetime.BaseLocalDateTimeUtil;
import cn.kgc.tangcco.utils.qiniuyun.BaseQiniuyunUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.model.PutObjectResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 李昊哲
 * @Description
 * @create 2020/9/6 上午8:51
 */
@RestController
@RequestMapping(value = "/fileupload")
public class FileUploadController {
    private static Props props = new Props("config.properties");
    private static String contetxtPath = props.getProperty("upload");
    private static String formatter = props.getProperty("formatter");
    private static String http_protocol = props.getProperty("http_protocol");
    private static String wftp_port = props.getProperty("wftp_port");
    private static String server = http_protocol + props.getProperty("ftpIp") + wftp_port;

    private static String ftp_host = props.getProperty("ftp_host");
    private static String ftp_port = props.getProperty("ftp_port");
    private static String ftp_user = props.getProperty("ftp_user");
    private static String ftp_password = props.getProperty("ftp_password");
    private static String charset = props.getProperty("charset");
    private static FtpConfig ftpConfig = new FtpConfig(ftp_host, Integer.parseInt(ftp_port), ftp_user, ftp_password, Charset.forName(charset));

    static {
        formatter = BaseDateUtil.format(new Date(), formatter);
    }

    @RequestMapping(value = "/upload01")
    public ResposeText<String> upload01(@RequestParam("header") MultipartFile multipartFile, HttpServletRequest request) {
        // 封装返回数据 默认上传失败
        ResposeText<String> resposeText = new ResposeText<String>(ResultCode.DATA_ERROR.getCode(), ResultCode.DATA_ERROR.getMsg(), null);
        // 获取源文件名字
        String originalFilename = multipartFile.getOriginalFilename();
        // 获取服务器在文件系统的真实路径
        String serverRootPath = request.getServletContext().getRealPath("/");
        //  ContetxtPath
        String contetxtPath = "/statics/upload/";
        // 文件被上传的路径
        String uploadPath = serverRootPath + contetxtPath;

        // 目标文件
        File dest = new File(uploadPath, originalFilename);
        try {
            // 将上传的文件保存到文件系统
            multipartFile.transferTo(dest);
            // 上传成功
            resposeText.setCode(ResultCode.SUCCESS.getCode());
            resposeText.setMsg(ResultCode.SUCCESS.getMsg());
            // 服务器端文件地址
            resposeText.setData(contetxtPath + originalFilename);
            System.out.println(JSON.toJSONString(resposeText));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return resposeText;
        }
    }

    @RequestMapping(value = "/upload02")
    public ResposeText<String> upload02(@RequestParam("header") MultipartFile multipartFile, HttpServletRequest request) {
        // 封装返回数据
        // 默认上传失败
        ResposeText<String> resposeText = new ResposeText<String>(ResultCode.DATA_ERROR.getCode(), ResultCode.DATA_ERROR.getMsg(), null);
        // 获取源文件名字
        String originalFilename = multipartFile.getOriginalFilename();
        // 获取服务器在文件系统的真实路径
        String serverRootPath = request.getServletContext().getRealPath("/");
        // 文件被上传的路径
        String uploadPath = serverRootPath + contetxtPath + formatter;
        //获得源文件后缀
        String suffix = FilenameUtils.getExtension(originalFilename);
        // 新文件名字
        String newFileName = IdUtil.fastSimpleUUID() + "." + suffix;
        System.out.println(newFileName);
        // 目标文件
        File dest = new File(uploadPath, newFileName);

        try {
            // 将上传的文件保存到文件系统
            multipartFile.transferTo(dest);
            // 上传成功
            resposeText.setCode(ResultCode.SUCCESS.getCode());
            resposeText.setMsg(ResultCode.SUCCESS.getMsg());
            // 服务器端文件地址
            resposeText.setData(contetxtPath + formatter + newFileName);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return resposeText;
        }
    }

    @RequestMapping(value = "/ftpupload01")
    public ResposeText<String> ftpupload01(@RequestParam("header") MultipartFile multipartFile, HttpServletRequest request) {
        // 封装返回数据 默认上传失败
        ResposeText<String> resposeText = new ResposeText<String>(ResultCode.DATA_ERROR.getCode(), ResultCode.DATA_ERROR.getMsg(), null);
        // 获取源文件名字
        String originalFilename = multipartFile.getOriginalFilename();
        // 文件被上传的路径
        String uploadPath = contetxtPath + formatter;
        //获得源文件后缀
        String suffix = FilenameUtils.getExtension(originalFilename);
        // 新文件名字
        String newFileName = IdUtil.fastSimpleUUID() + "." + suffix;
        System.out.println(newFileName);
        // 目标文件
        String dest = uploadPath + newFileName;

        // 实例化FTP客户端
        BaseFtpClient baseFtpClient = new BaseFtpClient();
        try {
            // 获取上传文件的字节输入流
            InputStream inputStream = multipartFile.getInputStream();
            // 登录服务器
            if (baseFtpClient.connectServer()) {
                // 登录成功后上传文件
                if (baseFtpClient.uploadFile(dest, inputStream)) {
                    // 上传成功
                    resposeText.setCode(ResultCode.SUCCESS.getCode());
                    resposeText.setMsg(ResultCode.SUCCESS.getMsg());
                    // 服务器端文件地址
                    resposeText.setData(server + contetxtPath + formatter + newFileName);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 退出服务器
            baseFtpClient.disconnectServer();
            return resposeText;
        }
    }

    @RequestMapping(value = "/ftpupload02")
    public ResposeText<String> ftpupload02(@RequestParam("header") MultipartFile multipartFile, HttpServletRequest request) {
        // 封装返回数据 默认上传失败
        ResposeText<String> resposeText = new ResposeText<String>(ResultCode.DATA_ERROR.getCode(), ResultCode.DATA_ERROR.getMsg(), null);
        // 获取源文件名字
        String originalFilename = multipartFile.getOriginalFilename();
        // 文件被上传的路径
        String uploadPath = contetxtPath + formatter;
        //获得源文件后缀
        String suffix = FilenameUtils.getExtension(originalFilename);
        // 新文件名字
        String newFileName = IdUtil.fastSimpleUUID() + "." + suffix;
        System.out.println(newFileName);

        // 实例化FTP客户端
        Ftp ftp = new Ftp(ftpConfig, FtpMode.Active);
        // 文件上传
        try {
            ftp.upload(uploadPath, newFileName, multipartFile.getInputStream());
            // 上传成功
            resposeText.setCode(ResultCode.SUCCESS.getCode());
            resposeText.setMsg(ResultCode.SUCCESS.getMsg());
            // 服务器端文件地址
            resposeText.setData(server + contetxtPath + formatter + newFileName);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 退出服务器
            try {
                ftp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return resposeText;
        }
    }

    @RequestMapping(value = "/fastdfs")
    public ResposeText<String> fastdfs(@RequestParam("header") MultipartFile multipartFile, HttpServletRequest request) {
        // 封装返回数据
        ResposeText<String> resposeText = new ResposeText<String>(ResultCode.DATA_ERROR.getCode(), ResultCode.DATA_ERROR.getMsg(), null);
        // 默认上传失败
        // 获取源文件名字
        String originalFilename = multipartFile.getOriginalFilename();
        //获得源文件后缀
        String suffix = FilenameUtils.getExtension(originalFilename);
        // 文件上传
        try {

            String url = BaseFastDFSUtil.upload(multipartFile.getInputStream(), suffix);
            // 上传成功
            resposeText.setCode(ResultCode.SUCCESS.getCode());
            resposeText.setMsg(ResultCode.SUCCESS.getMsg());
            // 服务器端文件地址
            resposeText.setData(url);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return resposeText;
        }
    }

    @RequestMapping(value = "/qiniuyun")
    public ResposeText<String> qiniuyun(@RequestParam("header") MultipartFile multipartFile, HttpServletRequest request) {
        // 封装返回数据
        ResposeText<String> resposeText = new ResposeText<String>(ResultCode.DATA_ERROR.getCode(), ResultCode.DATA_ERROR.getMsg(), null);
        // 默认上传失败
        try {
            // 文件上传
            Map<String, Object> map = BaseQiniuyunUtil.upload(multipartFile.getInputStream());
            resposeText.setCode((String) map.get("code"));
            resposeText.setMsg((String) map.get("msg"));
            resposeText.setData((String) map.get("url"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return resposeText;
        }
    }

    @RequestMapping(value = "/alioss")
    public ResposeText<String> alioss(@RequestParam("header") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        // 封装返回数据
        ResposeText<String> resposeText = new ResposeText<>(ResultCode.DATA_ERROR.getCode(), ResultCode.DATA_ERROR.getMsg(), null);

        String path = BaseLocalDateTimeUtil.format(LocalDateTime.now(), formatter);
        // 获取原始名字
        String originalFilename = multipartFile.getOriginalFilename();
        // 获取文件后缀名
        String extension = FilenameUtils.getExtension(originalFilename);
        // 生成新文件名
        String fileName = IdUtil.fastSimpleUUID() + "." + extension;
        // 上传路径+文件名
        String objectName = path + fileName;

        URL url = BaseAliOSSUtil.upload(multipartFile.getInputStream(), objectName);

        BaseAliOSSUtil.close();
        System.out.println(JSON.toJSONString(url));
        String imgPath = url.toString();
        resposeText.setCode(ResultCode.SUCCESS.getMsg());
        resposeText.setMsg(ResultCode.SUCCESS.getMsg());
        resposeText.setData(imgPath.substring(0, imgPath.indexOf("?")));
        return resposeText;
    }
}
